import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Seat } from './assets/seat.entity';
import { EntityManager, Repository } from 'typeorm';
import { util_Db_PageList, util_Db_Delete, util_Db_NoPageList } from '@/common/util/db';
import { IRequest } from '@/common/typeScripts/index';
import { Cron } from '@nestjs/schedule';
import { Good } from '../good/assets/good.entity';

@Injectable()
export class Seat_Service {
  constructor(
    @InjectRepository(Seat)
    private seat_Repository: Repository<Seat>,
    @InjectRepository(Good)
    private good_Repository: Repository<Good>,
    private entityManager: EntityManager,
  ) {}

  async seat_FindOneById(id: number) {
    return await this.seat_Repository
      .createQueryBuilder('seat')
      .andWhere(`seat.id = :id`, { id: id })
      .getOne();
  }

  async seat_FindByGoodId(id: number) {
    const queryBuilder = this.seat_Repository
      .createQueryBuilder('seat')
      .leftJoin('seat.userData', 'userData')
      .select(['seat.id AS id', 'userData.phone AS phone', 'userData.userName AS userName']);
    return await util_Db_NoPageList<Seat>({ queryBuilder, query: { goodId: id }, isRaw: true });
  }

  async seat_Remove(id: number) {
    return await util_Db_Delete({
      findOne: () => this.seat_FindOneById(id),
      id,
      repository: this.seat_Repository,
    });
  }

  async seat_Web_MySeat(req: IRequest) {
    console.log(req.user);

    return await util_Db_PageList<Seat>({
      queryBuilder: this.seat_Repository
        .createQueryBuilder('seat')
        .leftJoin('seat.good', 'good')
        .leftJoin('good.product', 'product')
        .select([
          'seat.id AS id',
          'good.account AS account',
          'good.password AS password',
          'product.productName AS productName',
          'product.productPrice AS productPrice',
          'seat.seatBuyTime AS seatBuyTime',
          'seat.invalidTime AS invalidTime',
        ]),
      query: {
        'seat.userClientId': req.user.userId,
      },
      isRaw: true,
    });
  }

  @Cron('0 0 3 * * *')
  async seat_InvalidHandle() {
    const date = new Date().getTime();
    const invalidList = await this.seat_Repository
      .createQueryBuilder('seat')
      .leftJoinAndSelect('seat.good', 'good')
      .andWhere(`seat.invalidTime >= :invalidTime`, { invalidTime: date })
      .getMany();
    invalidList.map(async (item) => {
      await this.entityManager.transaction(async (manage) => {
        const good = await this.good_Repository
          .createQueryBuilder('good')
          .andWhere(`good.id = :id`, { id: item.good.id })
          .getOne();
        good.seatsNum = good.seatsNum - 1;
        await manage.save(Good, good);
        await manage.delete(Seat, item.id);
      });
    });
  }
}
